package gw.com.android.upgrade;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.webkit.URLUtil;

import com.gwtsz.gts2.hx.R;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.ui.BaseActivity;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.app.ObjectSessionStore;

/**
 * 程序升级的Service
 * 
 */
public class AppUpgradeService extends Service {
	/** 下载文件的地址 */
	private String download_url = null;
	public static final int DOWNLOAD_BEGIN = 0; // 开始下载
	public static final int DOWNLOAD_ING = 1; // 下载中
	public static final int DOWNLOAD_FAIL = 2; // 下载失败
	public static final int DOWNLOAD_INSTALLED = 3; // 程序运行过程中,下载完成后自动跳转安装界面,清除通知栏

	private Handler upgradeHandler = null; // handler消息处理对象
	public static boolean isStartUpgrade = false; // 标识是否已经开启更新包下载服务
	public static boolean isUpgradeing = false; // 是否正在下载中

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		int retVal = super.onStartCommand(intent, flags, startId);

		isStartUpgrade = true;

		try {
			// by reeta 如果正在下载中，不需要再进行下载
			if (isUpgradeing) {
				return retVal;
			}

			if (null != intent && null != intent.getExtras()) {
				Bundle bundle = intent.getExtras();
				download_url = bundle.getString("url");
				upgradeHandler = (Handler) ObjectSessionStore.popObject(bundle.getString("upgradeHandler"));
				new DownloadAndInstallTask().start();
			}
		} catch (Exception e) {
			Logger.e(e);
		}

		return retVal;
	}

	/**
	 * 设置加载进度监听器
	 * 
	 */
	DataHttpConnectionListener mListener = new DataHttpConnectionListener() {
		@Override
		public void onStart() {
			isUpgradeing = true;
			upgradeHandler.sendEmptyMessage(DOWNLOAD_BEGIN);
		}

		@Override
		public void onFinished() {

		}

		@Override
		public void onReceiveProgress(int percent, long downloadedSize, long totalSize) {
			int currentProgress = (int) (downloadedSize * 100 / totalSize);

			Message msg1 = new Message();
			msg1.what = DOWNLOAD_ING;
			msg1.arg1 = currentProgress;
			Bundle bundle = new Bundle();
			bundle.putLong("downloadedSize", downloadedSize);
			bundle.putLong("totalSize", totalSize);
			msg1.setData(bundle);
			upgradeHandler.sendMessage(msg1);
		}

		@Override
		public void onError(String errorMessage) {
			Message msg = new Message();
			msg.obj = errorMessage; // 通知栏上显示当前出错信息
			msg.what = DOWNLOAD_FAIL;
			upgradeHandler.sendMessage(msg);
		}

		@Override
		public void onSuccess() {
			// 校验安装包
			upgradeHandler.sendEmptyMessage(DOWNLOAD_INSTALLED);
		}
	};

	private class DownloadAndInstallTask extends Thread {

		@Override
		public void run() {
			super.run();
			downloadFile();
		}

		/**
		 * 下载安装包代码
		 * 
		 */
		private void downloadFile() {
			if (!URLUtil.isNetworkUrl(download_url)) {
				final BaseActivity activity = (BaseActivity) AppActivities.getSingleton().currentActivity();
				activity.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						activity.showToastPopWindow(AppMain.getAppString(R.string.app_upgrade_url_error));

						if(null != UpdateDialog.instance()){
							UpdateDialog.instance().dismiss();
						}
					}
				});
				return;
			} else {
				URL downloadURL;
				try {
					downloadURL = new URL(download_url);
					int fileLength;
					isUpgradeing = true;
					mListener.onConnectionStart();
					if (downloadURL.getProtocol().equals("https")) {
						SSLContext sc = SSLContext.getInstance("TLS");
						sc.init(null, new TrustManager[] { new SimpleTrustManager() }, new SecureRandom());
						HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
						HttpsURLConnection.setDefaultHostnameVerifier(new SimpleHostnameVerifier());
						HttpsURLConnection httpsConn = (HttpsURLConnection) downloadURL.openConnection();
						httpsConn.connect();
						fileLength = httpsConn.getContentLength();
					} else {
						URLConnection conn = downloadURL.openConnection();
						conn.connect();
						fileLength = conn.getContentLength();
					}

					mListener.setReceiveTotalLength(fileLength);

					InputStream input = new BufferedInputStream(downloadURL.openStream());
					String fPath = GTConfig.instance().getRootDirectory() + "/" + AppMain.getAppString(R.string.apk_name);
					FileOutputStream output = new FileOutputStream(fPath);
					byte buf[] = new byte[64];
					int count;

					while ((count = input.read(buf)) > 0) {
						mListener.updateReceiveProgress(count);
						output.write(buf, 0, count);
					}
					input.close();
					output.close();
					isUpgradeing = false;
					mListener.onSuccess();
				} catch (MalformedURLException e) {
					e.printStackTrace();
					mListener.onError("");
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
					mListener.onError("");
				} catch (KeyManagementException e) {
					e.printStackTrace();
					mListener.onError("");
				} catch (IOException e) {
					e.printStackTrace();
					mListener.onError("");
				}finally {
					if (upgradeHandler != null) {
						upgradeHandler = null;
					}
				}
			}
		}
	}

	private class SimpleHostnameVerifier implements HostnameVerifier {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	private class SimpleTrustManager implements X509TrustManager {
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}

	@Override
	public ComponentName startService(Intent service) {
		isStartUpgrade = true;
		return super.startService(service);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		if (upgradeHandler != null) {
			upgradeHandler = null;
		}
		isStartUpgrade = false;
	}
}
